package com.ccp.dev.form.service;

import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.form.dao.FormRightsDao;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.model.FormRights;
import com.ccp.dev.form.model.FormTable;
import com.ccp.dev.form.util.FormUtil;
import com.ccp.dev.form.util.PlatformType;
import com.ccp.dev.form.util.UrlFormUtil;
import com.ccp.dev.system.model.Position;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.service.PositionService;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.system.service.SysRoleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Form_Rights service类
 *
 * @author caishaofan
 */
@Service
public class FormRightsService {

    @Resource
    private FormRightsDao formRightsDao;

    @Resource
    private FormDefService formDefService;

    @Resource
    private FormTableService formTableService;

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private PositionService positionService;
    @Resource
    private SysOrgService sysOrgService;

    /**
     * 根据流程定义id，任务节点id和表单id获取权限数据。
     *
     * @param actDefId 流程定义ID
     * @param nodeId   任务节点
     * @param formKey  表单定义ID
     * @return Map<String   ,   List   <   JSONObject>>
     */
    public Map<String, List<JSONObject>> getPermission(String formKey, String actDefId, String nodeId, String parentActDefId, Integer platform) {
        Map<String, List<JSONObject>> map = new HashMap<>(16);
        //具体节点的权限
        List<FormRights> rightList = getFormRightList(formKey, actDefId, nodeId, parentActDefId, platform);
        FormDef bpmFormDef = formDefService.getDefaultVersionByFormKey(formKey);
        //默认的权限
        if (BeanUtils.isEmpty(rightList)) {
            map = getPermissionByFormKey(bpmFormDef);
        } else {
            map = getPermissionByFormKey(rightList, bpmFormDef);
        }
        return map;
    }

    /**
     * 根据流程定义id，任务节点id和表单id获取URL权限数据。
     *
     * @param actDefId 流程定义ID
     * @param nodeId   任务节点
     * @param formKey  表单定义ID
     * @return Map<String                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               List                                                                                                                                                                                                                                                               <                                                                                                                                                                                                                                                               JSONObject>>
     */
    public Map<String, List<JSONObject>> getUrlFormPermission(HttpServletRequest request, String formKey, String actDefId, String nodeId, String parentActDefId, Integer platform) throws Exception {
        Map<String, List<JSONObject>> map;
        List<FormRights> rightList = getFormRightList(formKey, actDefId, nodeId, parentActDefId, platform);
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        //默认的权限
        if (BeanUtils.isEmpty(rightList)) {
            map = UrlFormUtil.parseUrlHtml(formKey, baseUrl, request);
        } else {
            map = UrlFormUtil.getPermissionByUrlFormKey(rightList, formKey, baseUrl, request);
        }
        return map;
    }

    /**
     * 根据流程定义id，任务节点id和表单id获取权限数据。
     *
     * @param formKey         表单定义ID
     * @param actDefId        流程定义ID
     * @param nodeId          节点ID
     * @param parentProcDefId 父流程节点ID
     * @param platform        平台类型
     * @return 权限列表数据
     */
    private List<FormRights> getFormRightList(String formKey, String actDefId, String nodeId, String parentProcDefId, Integer platform) {
        List<FormRights> rightList = null;
        //具体节点的权限
        if (StringUtil.isNotEmpty(nodeId)) {
            if (StringUtils.isNotEmpty(parentProcDefId)) {
                rightList = formRightsDao.getBpmFormRights(formKey, actDefId, false, nodeId, false, parentProcDefId, false, platform);
            } else {
                rightList = formRightsDao.getBpmFormRights(formKey, actDefId, false, nodeId, false, null, true, platform);
            }
        }
        //流程的全局菜单
        if (StringUtil.isNotEmpty(actDefId) && BeanUtils.isEmpty(rightList)) {
            if (StringUtils.isNotEmpty(parentProcDefId)) {
                rightList = formRightsDao.getBpmFormRights(formKey, actDefId, false, null, true, parentProcDefId, false, platform);
            } else {
                rightList = formRightsDao.getBpmFormRights(formKey, actDefId, false, null, true, null, true, platform);
            }
        }
        //表单管理的表单权限
        if (BeanUtils.isEmpty(rightList)) {
            rightList = formRightsDao.getBpmFormRights(formKey, null, true, null, true, null, true, platform);
        }
        return rightList;
    }

    /**
     * 给字段添加控件类型
     *
     * @param permission    字段权限JSONObject
     * @param controlType   控件类型
     * @param tableId       表id
     * @param tableName     表名
     * @param mainTableId   主表id
     * @param mainTableName 主表名
     */
    private void addControlType(JSONObject permission, Short controlType, String tableId, String tableName, String mainTableId, String mainTableName) {
        permission.put("controlType", controlType.toString());
        this.addRightsCommon(permission, tableId, tableName, mainTableId, mainTableName);
    }

    /**
     * 给字段添加公共的属性
     *
     * @param permission    字段权限JSONObject
     * @param tableId       表id
     * @param tableName     表名
     * @param mainTableId   主表id
     * @param mainTableName 主表名
     */
    private void addRightsCommon(JSONObject permission, String tableId, String tableName, String mainTableId, String mainTableName) {
        permission.put("tableId", tableId);
        permission.put("tableName", tableName);
        permission.put("mainTableId", mainTableId);
        permission.put("mainTableName", mainTableName);
    }


    /**
     * 获取通过表单设定定义表单的权限数据。
     *
     * <pre>
     * 通过设计定义的表单，
     * 如果有设置过权限，那么权限信息可以通过设置过权限与解析表单匹配获取。
     * </pre>
     *
     * @param rightList  List<FormRights>
     * @param bpmFormDef FormDef
     * @return Map<String   ,   List   <   JSONObject>>
     */
    private Map<String, List<JSONObject>> getPermissionByFormKey(List<FormRights> rightList, FormDef bpmFormDef) {
        Map<String, List<JSONObject>> map = new HashMap<>(4);
        if (BeanUtils.isEmpty(bpmFormDef)) {
            return map;
        }
        //分别为   主表字段权限 子表字段权限 意见权限 子表显示与否权限
        List<FormRights> formRightsList = new ArrayList<>();
        List<FormRights> tableRightsList = new ArrayList<>();
        List<FormRights> otherRightsList = new ArrayList<>();
        List<FormRights> tableShowRightsList = new ArrayList<>();
        //将权限分配到各个权限集合中
        FormUtil.fillRightsList(rightList, formRightsList, tableRightsList, otherRightsList, tableShowRightsList);
        FormTable bpmFormTable = formTableService.getByTableId(bpmFormDef.getTableId(), FormField.FIELD_NORMAL);
        if (BeanUtils.isEmpty(bpmFormTable)) {
            return map;
        }
        //主表字段权限
        List<JSONObject> fieldJsonList = new ArrayList<>();
        List<FormField> fieldList = bpmFormTable.getFieldList();
        for (FormField bpmFormField : fieldList) {
            boolean fieldIsNotExistPer = true;
            for (FormRights bpmFormRights : formRightsList) {
                if (StringUtil.isNotEmpty(bpmFormRights.getName()) && bpmFormRights.getName().equalsIgnoreCase(bpmFormField.getFieldName())) {
                    JSONObject permission = JSONObject.fromObject(bpmFormRights.getPermission());
                    if (!permission.containsKey("tableId")) {
                        this.addControlType(permission, bpmFormField.getControlType(), bpmFormTable.getTableId(), bpmFormTable.getTableName(), "", "");
                    } else {
                        permission.put("tableId", bpmFormTable.getTableId());
                    }
                    fieldJsonList.add(permission);
                    fieldIsNotExistPer = false;
                    break;
                }
            }
            //没有设置过匹配权限时直接到初始化中获取(兼容以前版本)
            if (fieldIsNotExistPer) {
                JSONObject permission = FormUtil.getPermissionJson(bpmFormField.getFieldName(), bpmFormField.getFieldDesc(), FormRights.FIELD_RIGHTS);
                this.addControlType(permission, bpmFormField.getControlType(), bpmFormDef.getTableId(), bpmFormDef.getTableName(), "", "");
                fieldJsonList.add(permission);
            }
        }
        map.put("field", fieldJsonList);

        //子表字段权限
        List<JSONObject> tableJsonList = new ArrayList<>();
        List<FormTable> tableList = bpmFormTable.getSubTableList();
        for (FormTable table : tableList) {
            // 子表整个表的权限
            JSONObject permission = FormUtil.getPermissionJson(table.getTableName(), table.getTableDesc(), FormRights.TABLE_RIGHTS);
            //每个子表中的每个字段
            List<FormField> subFieldList = table.getFieldList();
            List<JSONObject> subFieldJsonList = new ArrayList<>();
            for (FormField field : subFieldList) {
                boolean fieldIsNotExistPer = true;
                for (FormRights bpmFormRights : tableRightsList) {
                    if (StringUtil.isNotEmpty(bpmFormRights.getName()) && bpmFormRights.getName().equalsIgnoreCase(field.getFieldName())) {
                        JSONObject subPermission = JSONObject.fromObject(bpmFormRights.getPermission());
                        if (subPermission.containsKey("tableId") && subPermission.getString("tableId").equals(table.getTableId())) {
                            if (!subPermission.containsKey("mainTableId")) {
                                this.addControlType(subPermission, field.getControlType(), table.getTableId(), table.getTableName(), bpmFormTable.getTableId(), bpmFormTable.getTableName());
                            }
                            subFieldJsonList.add(subPermission);
                            fieldIsNotExistPer = false;
                            break;
                        }
                    }
                }
                if (fieldIsNotExistPer) {
                    //没有设置过匹配权限时直接到初始化中获取(兼容以前版本)
                    JSONObject subPermission = FormUtil.getPermissionJson(field.getFieldName(), field.getFieldDesc(), FormRights.FIELD_RIGHTS);
                    this.addControlType(subPermission, field.getControlType(), table.getTableId(), table.getTableName(), bpmFormTable.getTableId(), bpmFormTable.getTableName());
                    subFieldJsonList.add(subPermission);
                }
            }
            //子表整个表的权限是重新生成的，所以不用判断
            this.addRightsCommon(permission, table.getTableId(), table.getTableName(), bpmFormTable.getTableId(), bpmFormTable.getTableName());
            permission.put("subField", subFieldJsonList);
            tableJsonList.add(permission);
        }
        map.put("table", tableJsonList);

        //处理其它  意见权限。
        // 获取模版。
        String html = bpmFormDef.getHtml();
        List<JSONObject> opinionJsonList = new ArrayList<>();
        if (StringUtil.isNotEmpty(html)) {
            Map<String, String> opinionMap = FormUtil.parseOpinion(html);
            Set<Map.Entry<String, String>> set = opinionMap.entrySet();
            for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext(); ) {
                boolean opinionIsNotExistPer = true;
                Map.Entry<String, String> tmp = it.next();
                for (FormRights bpmFormRights : otherRightsList) {
                    JSONObject opinionPermission = JSONObject.fromObject(bpmFormRights.getPermission());
                    if (StringUtil.isNotEmpty(bpmFormRights.getName()) && bpmFormRights.getName().equalsIgnoreCase(tmp.getKey())) {
                        if (!opinionPermission.containsKey("tableId")) {
                            this.addRightsCommon(opinionPermission, bpmFormTable.getTableId(), bpmFormTable.getTableName(), "", "");
                        } else {
                            opinionPermission.put("tableId", bpmFormTable.getTableId());
                        }
                        opinionJsonList.add(opinionPermission);
                        opinionIsNotExistPer = false;
                        break;
                    }
                }
                if (opinionIsNotExistPer) {
                    //没有设置过匹配权限时直接到初始化中获取(兼容以前版本)
                    JSONObject permission = FormUtil.getPermissionJson(tmp.getKey(), tmp.getValue(), FormRights.OPINION_RIGHTS);
                    this.addRightsCommon(permission, bpmFormTable.getTableId(), bpmFormTable.getTableName(), "", "");
                    opinionJsonList.add(permission);
                }
            }
        }
        map.put("opinion", opinionJsonList);
        //子表显示与否
        List<JSONObject> tableShowJsonList = new ArrayList<>();
        for (FormTable table : tableList) {
            boolean subTableIsNotExistPer = true;
            for (FormRights bpmFormRights : tableShowRightsList) {
                if (StringUtil.isNotEmpty(bpmFormRights.getName()) && bpmFormRights.getName().equalsIgnoreCase(table.getTableName())) {
                    JSONObject permission = JSONObject.fromObject(bpmFormRights.getPermission());
                    if (!permission.containsKey("tableId")) {
                        this.addRightsCommon(permission, table.getTableId(), table.getTableName(), bpmFormTable.getTableId(), bpmFormTable.getTableName());
                    } else {
                        permission.put("tableId", table.getTableId());
                        permission.put("mainTableId", bpmFormTable.getTableId());
                    }
                    tableShowJsonList.add(permission);
                    subTableIsNotExistPer = false;
                    break;
                }
            }
            if (subTableIsNotExistPer) {
                //没有设置过匹配权限权限时直接到初始化中获取(兼容以前版本)
                JSONObject permission = FormUtil.getPermissionJson(table.getTableName(), table.getTableDesc(), FormRights.TABLE_SHOW_RIGHTS);
                this.addRightsCommon(permission, table.getTableId(), table.getTableName(), bpmFormTable.getTableId(), bpmFormTable.getTableName());
                tableShowJsonList.add(permission);
            }
        }
        map.put("tableShow", tableShowJsonList);
        return map;
    }


    /**
     * 获取通过表单设定定义表单的权限数据。
     *
     * <pre>
     * 通过设计定义的表单，
     * 如果没有还没有设置过权限，那么权限信息可以通过解析表单获取。
     * </pre>
     *
     * @param bpmFormDef FormDef
     * @return Map<String                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               List                                                                                                                                                                                                                                                               <                                                                                                                                                                                                                                                               JSONObject>>
     */
    public Map<String, List<JSONObject>> getPermissionByFormKey(FormDef bpmFormDef) {
        Map<String, List<JSONObject>> map = new HashMap<>(4);
        // 获取模版。
        String html = bpmFormDef.getHtml();
        String tableId = bpmFormDef.getTableId();
        // 读取表。
        FormTable bpmFormTable = formTableService.getByTableId(tableId, FormField.FIELD_NORMAL);
        // 主表字段权限
        List<FormField> fieldList = bpmFormTable.getFieldList();
        List<JSONObject> fieldJsonList = new ArrayList<>();
        for (FormField field : fieldList) {
            JSONObject permission = FormUtil.getPermissionJson(field.getFieldName(), field.getFieldDesc(), FormRights.FIELD_RIGHTS);
            this.addControlType(permission, field.getControlType(), tableId, bpmFormTable.getTableName(), "", "");
            fieldJsonList.add(permission);
        }
        map.put("field", fieldJsonList);

        // 子表权限。
        List<JSONObject> tableJsonList = new ArrayList<>();
        List<FormTable> tableList = bpmFormTable.getSubTableList();
        for (FormTable table : tableList) {
            // 子表整个表的权限
            JSONObject permission = FormUtil.getPermissionJson(table.getTableName(), table.getTableDesc(), FormRights.TABLE_RIGHTS);
            //每个子表中的每个字段
            List<FormField> subFieldList = table.getFieldList();
            List<JSONObject> subFieldJsonList = new ArrayList<>();
            for (FormField field : subFieldList) {
                JSONObject subPermission = FormUtil.getPermissionJson(field.getFieldName(), field.getFieldDesc(), FormRights.FIELD_RIGHTS);
                this.addControlType(subPermission, field.getControlType(), table.getTableId(), table.getTableName(), tableId, bpmFormTable.getTableName());
                subFieldJsonList.add(subPermission);
            }
            this.addRightsCommon(permission, table.getTableId(), table.getTableName(), tableId, bpmFormTable.getTableName());
            permission.put("subField", subFieldJsonList);
            tableJsonList.add(permission);
        }
        map.put("table", tableJsonList);

        // 意见权限。
        List<JSONObject> opinionJsonList = new ArrayList<>();
        if (StringUtil.isNotEmpty(html)) {
            Map<String, String> opinionMap = FormUtil.parseOpinion(html);
            Set<Map.Entry<String, String>> set = opinionMap.entrySet();
            for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext(); ) {
                Map.Entry<String, String> tmp = it.next();
                JSONObject permission = FormUtil.getPermissionJson(tmp.getKey(), tmp.getValue(), FormRights.OPINION_RIGHTS);
                this.addRightsCommon(permission, tableId, bpmFormTable.getTableName(), "", "");
                opinionJsonList.add(permission);
            }
        }
        map.put("opinion", opinionJsonList);

        //子表显示与否
        List<JSONObject> tableShowJsonList = new ArrayList<>();
        for (FormTable table : tableList) {
            JSONObject permission = FormUtil.getPermissionJson(table.getTableName(), table.getTableDesc(), FormRights.TABLE_SHOW_RIGHTS);
            this.addRightsCommon(permission, table.getTableId(), table.getTableName(), tableId, bpmFormTable.getTableName());
            tableShowJsonList.add(permission);
        }
        map.put("tableShow", tableShowJsonList);
        return map;
    }

    /**
     * 保存表单权限。
     *
     * @param formKey    表单KEY
     * @param permission 权限JSON数据。
     * @throws Exception 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(String formKey, JSONObject permission, Integer platform) throws Exception {
        this.save(null, null, formKey, permission, "", platform);
    }

    /**
     * 保存任务节点权限。
     *
     * @param actDefId       流程定义id
     * @param nodeId         流程节点id
     * @param formKey        表单key
     * @param permission     权限JSON数据
     * @param parentActDefId 父流程定义id
     * @param platform       平台类型
     * @throws Exception 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(String actDefId, String nodeId, String formKey, JSONObject permission, String parentActDefId, Integer platform) throws Exception {
        FormDef bpmFormDef = formDefService.getDefaultVersionByFormKey(formKey);
        Map<String, FormField[]> selectorFieldMap = new HashMap<>(16);
        if (BeanUtils.isNotEmpty(bpmFormDef)) {
            selectorFieldMap = formTableService.getExecutorSelectorField(bpmFormDef.getTableId());
        }
        //子流程表单权限
        if (StringUtil.isEmpty(parentActDefId)) {
            this.save(actDefId, nodeId, formKey, permission, selectorFieldMap, platform);
        } else {
            this.save(actDefId, nodeId, formKey, permission, selectorFieldMap, parentActDefId, platform);
        }
    }

    /**
     * 抽离公共的 将权限model放入list
     *
     * @param obj       Object
     * @param formKey   表单key
     * @param platform  平台
     * @param actDefId  流程定义id。
     * @param nodeId    流程节点id。
     * @param list      List<FormRights>
     * @param formRight 字段类型
     */
    private void formRightsToList(Object obj, String formKey, Integer platform, String actDefId, String nodeId, List<FormRights> list, Short formRight) {
        String json = obj.toString();
        JSONObject jsonObj = (JSONObject) obj;
        String name = (String) jsonObj.get("title");
        FormRights bpmFormRights = new FormRights(UUIDUtils.getUUIDFor32(), formKey, name, json, formRight, platform);
        bpmFormRights.setActDefId(actDefId);
        bpmFormRights.setNodeId(nodeId);
        list.add(bpmFormRights);
    }

    /**
     * 抽离公共的 将权限model放入list，无参数platform
     *
     * @param obj       Object
     * @param formKey   表单key
     * @param actDefId  流程定义id。
     * @param nodeId    流程节点id。
     * @param list      List<FormRights>
     * @param formRight 字段类型
     */
    private void formRightsToListNoPlat(Object obj, String formKey, String actDefId, String nodeId, String parentActDefId, List<FormRights> list, Short formRight) {
        String json = obj.toString();
        JSONObject jsonObj = (JSONObject) obj;
        String name = (String) jsonObj.get("title");
        FormRights bpmFormRights = new FormRights(UUIDUtils.getUUIDFor32(), formKey, name, json, formRight);
        bpmFormRights.setActDefId(actDefId);
        bpmFormRights.setNodeId(nodeId);
        bpmFormRights.setParentActDefId(parentActDefId);
        list.add(bpmFormRights);
    }

    /**
     * 保存任务节点权限。
     *
     * @param actDefId   流程定义id
     * @param nodeId     流程节点id
     * @param formKey    表单别名
     * @param permission 权限JSON数据。
     * @throws Exception 异常
     */
    private void save(String actDefId, String nodeId, String formKey, JSONObject permission, Map<String, FormField[]> selectorFieldMap, Integer platform) throws Exception {
        //主表属性字段
        JSONArray fieldPermissions = permission.getJSONArray("field");
        //子表属性字段
        JSONArray tablePermissions = permission.getJSONArray("subTable");
        //意见
        JSONArray opinionPermissions = permission.getJSONArray("opinion");
        //子表 显示隐藏控制
        JSONArray subTableShows = permission.getJSONArray("subTableShow");
        List<FormRights> list = new ArrayList<>();

        // 表单字段权限。
        if (StringUtil.isNotEmpty(nodeId)) {
            formRightsDao.delByActDefIdAndNodeId(actDefId, nodeId, platform);
        } else if (StringUtil.isNotEmpty(actDefId)) {
            formRightsDao.delByActDefIdExcNode(actDefId, platform);
        } else {
            formRightsDao.delByFormKeyExcActDefId(formKey, platform);
        }

        if (BeanUtils.isNotEmpty(fieldPermissions)) {
            for (Object obj : fieldPermissions) {
                String json = obj.toString();
                JSONObject jsonObj = (JSONObject) obj;
                String name = (String) jsonObj.get("title");
                FormRights bpmFormRights = new FormRights(UUIDUtils.getUUIDFor32(), formKey, name, json, FormRights.FIELD_RIGHTS, platform);
                bpmFormRights.setNodeId(nodeId);
                bpmFormRights.setActDefId(actDefId);
                list.add(bpmFormRights);
                if (selectorFieldMap.containsKey(name)) {
                    String idName = selectorFieldMap.get(name)[1].getFieldName();
                    JSONObject idJson = JSONObject.fromObject(json);
                    idJson.element("title", idName);
                    String idJsonStr = idJson.toString();
                    FormRights hiddenIdRights = (FormRights) bpmFormRights.clone();
                    hiddenIdRights.setId(UUIDUtils.getUUIDFor32());
                    hiddenIdRights.setName(idName);
                    hiddenIdRights.setPermission(idJsonStr);
                    list.add(hiddenIdRights);
                }
            }
        }
        // 子表权限。
        if (BeanUtils.isNotEmpty(tablePermissions)) {
            for (Object obj : tablePermissions) {
                this.formRightsToList(obj, formKey, platform, actDefId, nodeId, list, FormRights.TABLE_RIGHTS);
            }
        }
        // 表单意见权限。
        if (BeanUtils.isNotEmpty(opinionPermissions)) {
            for (Object obj : opinionPermissions) {
                this.formRightsToList(obj, formKey, platform, actDefId, nodeId, list, FormRights.OPINION_RIGHTS);
            }
        }
        //子表的显示与否
        if (BeanUtils.isNotEmpty(subTableShows)) {
            for (Object obj : subTableShows) {
                this.formRightsToList(obj, formKey, platform, actDefId, nodeId, list, FormRights.TABLE_SHOW_RIGHTS);
            }
        }
        for (FormRights right : list) {
            formRightsDao.add(right);
        }
    }

    /**
     * 保存任务节点权限。
     *
     * @param actDefId   流程定义id
     * @param nodeId     流程节点id
     * @param formKey    表单别名
     * @param permission 权限JSON数据。
     * @throws Exception 异常
     */
    private void save(String actDefId, String nodeId, String formKey, JSONObject permission, Map<String, FormField[]> selectorFieldMap, String parentActDefId, Integer platform) throws Exception {
        JSONArray fieldPermissions = permission.getJSONArray("field");
        JSONArray tablePermissions = permission.getJSONArray("subTable");
        JSONArray subTableShows = permission.getJSONArray("subTableShow");
        JSONArray opinionPermissions = permission.getJSONArray("opinion");
        List<FormRights> list = new ArrayList<>();

        // 表单字段权限。
        if (StringUtil.isNotEmpty(nodeId)) {
            formRightsDao.delByActDefIdAndNodeIdAndParentActDefId(actDefId, nodeId, parentActDefId, platform);
        } else if (StringUtil.isNotEmpty(actDefId)) {
            formRightsDao.delByActDefIdAndParentActDefIdExcNode(actDefId, parentActDefId, platform);
        } else {
            formRightsDao.delByFormKeyExcActDefId(formKey, platform);
        }

        if (BeanUtils.isNotEmpty(fieldPermissions)) {
            for (Object obj : fieldPermissions) {
                String json = obj.toString();
                JSONObject jsonObj = (JSONObject) obj;
                String name = (String) jsonObj.get("title");
                FormRights bpmFormRights = new FormRights(UUIDUtils.getUUIDFor32(), formKey, name, json, FormRights.FIELD_RIGHTS);
                bpmFormRights.setNodeId(nodeId);
                bpmFormRights.setActDefId(actDefId);
                bpmFormRights.setParentActDefId(parentActDefId);
                list.add(bpmFormRights);
                if (selectorFieldMap.containsKey(name)) {
                    String idName = selectorFieldMap.get(name)[1].getFieldName();
                    JSONObject idJson = JSONObject.fromObject(json);
                    idJson.element("title", idName);
                    String idJsonStr = idJson.toString();
                    FormRights hiddenIdRights = (FormRights) bpmFormRights.clone();
                    hiddenIdRights.setName(idName);
                    hiddenIdRights.setId(UUIDUtils.getUUIDFor32());
                    hiddenIdRights.setPermission(idJsonStr);
                    bpmFormRights.setParentActDefId(parentActDefId);
                    list.add(hiddenIdRights);
                }
            }
        }
        // 子表权限。
        if (BeanUtils.isNotEmpty(tablePermissions)) {
            for (Object obj : tablePermissions) {
                this.formRightsToListNoPlat(obj, formKey, actDefId, nodeId, parentActDefId, list, FormRights.TABLE_RIGHTS);
            }
        }
        // 表单意见权限。
        if (BeanUtils.isNotEmpty(opinionPermissions)) {
            for (Object obj : opinionPermissions) {
                this.formRightsToListNoPlat(obj, formKey, actDefId, nodeId, parentActDefId, list, FormRights.OPINION_RIGHTS);
            }
        }
        //子表的显示与否
        if (BeanUtils.isNotEmpty(subTableShows)) {
            for (Object obj : subTableShows) {
                this.formRightsToListNoPlat(obj, formKey, actDefId, nodeId, parentActDefId, list, FormRights.TABLE_SHOW_RIGHTS);
            }
        }
        for (FormRights right : list) {
            formRightsDao.add(right);
        }
    }

    /**
     * 根据表单键删除权限
     *
     * @param formKey      表单别名
     * @param cascade      是同时否删除表单的流程的流程节点表单权限设置
     * @param platformType 平台类型
     */
    public void delByFormKey(String formKey, boolean cascade, PlatformType platformType) {

        Map<String, Object> params = new HashMap<>(16);
        params.put("formKey", formKey);
        if (platformType != null && PlatformType.undefine != platformType) {
            params.put("platform", platformType.toString());
        }
        if (cascade) {
            formRightsDao.delByFormKey(params);
        } else {
            formRightsDao.delByFormKeyExcActDefId(params);
        }
    }

    /**
     * 获取默认只读的的权限数据。
     *
     * @param title
     * @param memo
     * @param type
     * @return
     */
    public JSONObject getReadPermissionJson(String title, String memo, int type) {
        //	String defJson = "{type:'everyone',id:'', fullname:''}";
        String defJson = "{type:'none',id:'', fullname:''}";
        JSONObject json = new JSONObject();
        json.element("title", title);
        json.element("memo", memo);
        if (type != 4) {
            json.element("read", "{type:'everyone',id:'', fullname:''}");
            json.element("write", defJson);
            if (type != 2) {
                json.element("required", defJson);
            }
        } else {
            //子表可增加记录：addRow:'true'  子表不可添加记录：addRow:'false'   可以增加默认
            json.element("show", "{addRow:'false'}");
        }
        return json;
    }

    /**
     * 获取默认的权限数据。
     *
     * @param title
     * @param memo
     * @param type
     * @return
     */
    public JSONObject getPermissionJson(String title, String memo, int type) {
        String defJson = "{type:'everyone',id:'', fullname:''}";
        JSONObject json = new JSONObject();
        json.element("title", title);
        json.element("memo", memo);
        if (type != 4) {
            json.element("read", defJson);
            json.element("write", defJson);
            if (type != 2) {
                json.element("required", "{type:'none',id:'', fullname:''}");
            }
        } else {
            //子表显示可写：w  子表显示只读：r  为显示  其它为隐藏（y）   可以增加默认
            json.element("show", "{addBtn:'true'}");
        }
        return json;
    }

    /**
     * 获取子表显示权限
     *
     * @param procDefId
     * @param nodeId
     * @param platformType
     * @return
     */
    public List<JSONObject> getSubTableShowRights(String procDefId, String nodeId, PlatformType platformType) {
        FormDef bpmFormDef = formDefService.getNodeFormDef(procDefId, nodeId, true);
        if (bpmFormDef == null) {
            return new ArrayList<>();
        }
        String formKey = bpmFormDef.getFormKey();
        List<FormRights> rightList = getRightList(formKey, procDefId, nodeId, null, platformType);

        List<JSONObject> subTableShowList = new ArrayList<>();
        for (FormRights rights : rightList) {
            //整个子表显示与否
            if (rights.getType() != FormRights.TABLE_SHOW_RIGHTS) {
                continue;
            }
            JSONObject permission = JSONObject.fromObject(rights.getPermission());
            subTableShowList.add(permission);
        }
        return subTableShowList;
    }

    private List<FormRights> getRightList(String formKey, String procDefId, String nodeId, String parentProcDefId, PlatformType platformType) {
        List<FormRights> rightList = null;
        String platform = "";
        // 如果流程定义id和任务节点id不为空那么获取节点的权限。
        if (platformType != null && PlatformType.undefine != platformType) {
            platform = platformType.toString();
        }
        if (StringUtil.isNotEmpty(procDefId) && StringUtil.isNotEmpty(nodeId)) {
            rightList = formRightsDao.getByActDefIdAndNodeId(formKey, procDefId, nodeId, parentProcDefId, Long.parseLong(platform));
        }
        if (BeanUtils.isEmpty(rightList) && StringUtil.isNotEmpty(procDefId)) {
            rightList = formRightsDao.getByActDefIdExcNodeId(formKey, procDefId, parentProcDefId, Long.parseLong(platform));
        }
        if (BeanUtils.isEmpty(rightList)) {
            rightList = formRightsDao.getByFormKeyExcActDefId(formKey, Long.parseLong(platform));
        }
        return rightList;
    }

    /**
     * 获取表单只读权限
     *
     * @param bpmFormDef 表单
     * @return
     */
    public Map<String, Map<String, String>> getByFormKey(FormDef bpmFormDef) {

        Map<String, Map<String, String>> permissions = new HashMap<>(16);
        Map<String, String> fieldPermission = new HashMap<>(16);
        Map<String, String> tablePermission = new HashMap<>(16);
        Map<String, String> opinionPermission = new HashMap<>(16);
        String right = "r";

        String html = bpmFormDef.getHtml();
        String tableId = bpmFormDef.getTableId();
        // 读取表。
        FormTable bpmFormTable = formTableService.getOneById(tableId);
        // 主表字段权限
        List<FormField> fieldList = bpmFormTable.getFieldList();
        for (FormField field : fieldList) {
            fieldPermission.put(field.getFieldName().toLowerCase(), right);
        }
        permissions.put("field", fieldPermission);

        // 子表权限。
        List<FormTable> tableList = bpmFormTable.getSubTableList();

        for (FormTable table : tableList) {
            // 子表字段权限
            List<FormField> subFieldList = table.getFieldList();
            for (FormField field : subFieldList) {
                tablePermission.put(field.getFieldName().toLowerCase(), right);
            }
        }
        permissions.put("table", tablePermission);

        // 意见权限。
        Map<String, String> opinionMap = FormUtil.parseOpinion(html);
        Set<Map.Entry<String, String>> set = opinionMap.entrySet();
        for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext(); ) {
            Map.Entry<String, String> tmp = it.next();
            opinionPermission.put(tmp.getKey().toLowerCase(), right);
        }
        permissions.put("opinion", opinionPermission);
        return permissions;
    }

    /**
     * 获取通过表单设定定义表单的权限数据。
     * 通过设计定义的表单，如果有设置过权限，那么权限信息可以通过设置过权限与解析表单匹配获取。
     *
     * @param formKey
     * @param userId
     * @param actDefId
     * @param nodeId
     * @param platformType
     * @return
     */
    public Map<String, List<JSONObject>> getSubTablePermission(String formKey, String userId, String actDefId, String nodeId, PlatformType platformType) {
        Map<String, List<JSONObject>> map = new HashMap<>(20);
        List<FormRights> rightList = getRightList(formKey, actDefId, nodeId, null, platformType);

        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        List<Position> positions = positionService.queryByUserId(userId);
        SysOrg org = sysOrgService.getOrgByUserId(userId);

        List<JSONObject> subJsonList = new ArrayList<>();
        List<JSONObject> subTableShowList = new ArrayList<>();
        for (FormRights rights : rightList) {
            //子表字段
            if (rights.getType() == FormRights.TABLE_RIGHTS) {
                JSONObject permission = JSONObject.fromObject(rights.getPermission());
                // 取得权限
                String right = getRight(permission, roles, positions, org, userId);
                //只读提交
                if ("r".equals(right)) {
                    boolean rpost = false;
                    if (permission.containsKey("rpost")) {
                        rpost = permission.getBoolean("rpost");
                    }
                    if (rpost) {
                        right = "rp";
                    }
                }
                permission.put("power", right);
                subJsonList.add(permission);
                //整个子表显示与否
            } else if (rights.getType() == FormRights.TABLE_SHOW_RIGHTS) {
                JSONObject permission = JSONObject.fromObject(rights.getPermission());
                subTableShowList.add(permission);
            }
        }
        map.put("subFileJsonList", subJsonList);
        map.put("subTableShowList", subTableShowList);
        return map;
    }

    /**
     * 获取通过表单设定定义表单的权限数据。(子表)
     * 通过设计定义的表单，如果有设置过权限，那么权限信息可以通过设置过权限与解析表单匹配获取。
     *
     * @param formKey
     * @param userId
     * @param procDefId
     * @param nodeId
     * @param platformType
     * @return
     */
    public Map<String, List<JSONObject>> getSubTablePermission(String formKey, String userId, String procDefId, String nodeId, String parentProcDefId, PlatformType platformType) {
        Map<String, List<JSONObject>> map = new HashMap<>(16);
        List<FormRights> rightList = getRightList(formKey, procDefId, nodeId, parentProcDefId, platformType);
        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        List<Position> positions = positionService.queryByUserId(userId);
        SysOrg org = sysOrgService.getOrgByUserId(userId);

        List<JSONObject> subJsonList = new ArrayList<>();
        List<JSONObject> oldSubJsonList = new ArrayList<>();
        List<JSONObject> subTableShowList = new ArrayList<>();
        for (FormRights rights : rightList) {
            //子表字段
            if (rights.getType() == FormRights.TABLE_RIGHTS) {
                JSONObject permission = JSONObject.fromObject(rights.getPermission());
                // 取得权限
                String right = getRight(permission, roles, positions, org, userId);
                //只读提交
                if ("r".equals(right)) {
                    boolean rpost = false;
                    if (permission.containsKey("rpost")) {
                        rpost = permission.getBoolean("rpost");
                    }
                    if (rpost) {
                        right = "rp";
                    }
                }
                permission.put("power", right);
                if (permission.containsKey("tableId")) {
                    subJsonList.add(permission);
                } else {
                    oldSubJsonList.add(permission);
                }
                //整个子表显示与否
            } else if (rights.getType() == FormRights.TABLE_SHOW_RIGHTS) {
                JSONObject permission = JSONObject.fromObject(rights.getPermission());
                subTableShowList.add(permission);
            }
        }
        map.put("subFileJsonList", subJsonList);
        map.put("oldSubFileJsonList", oldSubJsonList);
        map.put("subTableShowList", subTableShowList);
        return map;
    }


    /**
     * 获取权限。
     *
     * @param jsonObject 数据格式为：{
     *                   'title':'orderId','memo':'订单ID','read':{'type':'everyone','id':'',
     *                   'fullname':''},'write':{'type':'everyone','id':'',
     *                   'fullname':''}}
     * @param roles      用户所属的角色
     * @param positions  用户所属的岗位
     * @param org        用户所在的组织
     * @param userId     用户ID
     * @return
     */
    private String getRight(JSONObject jsonObject, List<SysRole> roles,
                            List<Position> positions, SysOrg org,
                            String userId) {
        String right = "";
        if (hasRight(jsonObject, "required", roles, positions, org, userId)) {
            right = "b";
        } else if (hasRight(jsonObject, "write", roles, positions, org, userId)) {
            right = "w";
        } else if (hasRight(jsonObject, "read", roles, positions, org, userId)) {
            right = "r";
        }
        return right;
    }

    /**
     * 判断是否有权限。
     *
     * @param permission 权限JSONOjbect
     * @param mode       读或写 (write,read)
     * @param roles      角色列表
     * @param positions  岗位
     * @param org        组织
     * @param userId     用户ID
     * @return
     */
    private boolean hasRight(JSONObject permission, String mode,
                             List<SysRole> roles, List<Position> positions, SysOrg org,
                             String userId) {
        boolean hasRight;
        JSONObject node = permission.getJSONObject(mode);
        if (JSONUtils.isNull(node)) {
            return false;
        }
        if (BeanUtils.isEmpty(node.get("type"))) {
            return false;
        }
        String type = node.get("type").toString();
        String id = "";
        if (node.has("id")) {
            id = node.get("id").toString();
        }
        if ("none".equals(type)) {
            return false;
        }
        if ("everyone".equals(type)) {
            return true;
        }
        // 指定用户
        if ("user".equals(type)) {
            hasRight = contain(id, userId);
            return hasRight;
        }
        // 指定角色
        else if ("role".equals(type)) {
            for (SysRole role : roles) {
                if (contain(id, role.getRoleId())) {
                    return true;
                }
            }
        }
        // 指定组织
        else if ("org".equals(type)) {
            if (contain(id, org.getOrgId())) {
                return true;
            }
        }
        // 岗位
        else if ("pos".equals(type)) {
            for (Position position : positions) {
                if (contain(id, position.getPosId())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判定逗号分隔的字符串是否包括指定的字符。
     *
     * @param ids
     * @param curId
     * @return
     */
    private boolean contain(String ids, String curId) {
        if (StringUtil.isEmpty(ids)) {
            return false;
        }
        String[] aryId = ids.split(",");
        for (String id : aryId) {
            if (id.equalsIgnoreCase(curId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据用户获得权限 field：{"NAME": "w", "SEX": "r"}
     * table：{"TABLE1": "r", "TABLE2": "w"}
     * opinion：{"领导意见": "w", "部门意见": "r"}
     *
     * @param formKey
     * @param userId
     * @param actDefId
     * @param nodeId
     * @param platformType
     * @return
     */
    public Map<String, Map<String, String>> getByFormKeyAndUserId(String formKey,
                                                                  String userId, String actDefId, String nodeId, PlatformType platformType) {
        List<FormRights> rightList = getRightList(formKey, actDefId, nodeId, null, platformType);

        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        List<Position> positions = positionService.queryByUserId(userId);
        SysOrg org = sysOrgService.getOrgByUserId(userId);

        Map<String, Map<String, String>> permissions = new HashMap<>(16);

        Map<String, String> fieldPermission = new HashMap<>(16);
        Map<String, String> tablePermission = new HashMap<>(16);
        Map<String, String> opinionPermission = new HashMap<>(16);
        Map<String, String> menuRightPermission = new HashMap<>(16);

        for (FormRights rights : rightList) {
            //子表显示权限不用进行读写权限判断
            if (FormRights.TABLE_SHOW_RIGHTS != rights.getType()) {
                JSONObject permission = JSONObject.fromObject(rights
                        .getPermission());
//                String name = rights.getName().toLowerCase();
                String name = rights.getName();
                // 取得权限
                String right = getRight(permission, roles, positions, org, userId);

                //只读提交
                if ("r".equals(right)) {
                    boolean rpost = false;
                    if (permission.containsKey("rpost")) {
                        rpost = permission.getBoolean("rpost");
                    }
                    if (rpost) {
                        right = "rp";
                    }
                }

                if (permission.containsKey("menuRight")) {

                    JSONObject menuRight = permission.getJSONObject("menuRight");
                    menuRightPermission.put(name, menuRight.toString());
                }

                switch (rights.getType()) {
                    case FormRights.FIELD_RIGHTS:
                        fieldPermission.put(name, right);
                        break;
                    case FormRights.TABLE_RIGHTS:
                        tablePermission.put(name, right);
                        break;
                    case FormRights.OPINION_RIGHTS:
                        opinionPermission.put(name, right);
                        break;
                    default:
                        break;
                }
            }
        }
        permissions.put("field", fieldPermission);
        permissions.put("table", tablePermission);
        permissions.put("opinion", opinionPermission);
        permissions.put("menuRight", menuRightPermission);
        return permissions;
    }

    /**
     * 根据用户获得权限（子流程）
     *
     * @param formKey         表单key
     * @param userId          用户id
     * @param procDefId       流程定义id
     * @param nodeId          节点id
     * @param parentProcDefId 父流程定义id
     * @return
     */
    public Map<String, Map<String, String>> getByFormKeyAndUserId(String formKey, String userId, String procDefId, String nodeId, String parentProcDefId, PlatformType platformType) {
        Integer platform = 1;
        List<FormRights> rightList = getFormRightList(formKey, procDefId, nodeId, parentProcDefId, platform);
        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        List<Position> positions = positionService.queryByUserId(userId);
        SysOrg sysOrg = sysOrgService.getOrgByUserId(userId);

        Map<String, Map<String, String>> permissions = new HashMap<>(16);
        Map<String, String> fieldPermission = new HashMap<>(16);
        Map<String, String> tablePermission = new HashMap<>(16);
        Map<String, String> opinionPermission = new HashMap<>(16);

        for (FormRights rights : rightList) {
            //子表显示权限不用进行读写权限判断
            if (FormRights.TABLE_SHOW_RIGHTS != rights.getType()) {
                JSONObject permission = JSONObject.fromObject(rights
                        .getPermission());
                String name = rights.getName().toLowerCase();
                // 取得权限
                String right = getRight(permission, roles, positions, sysOrg, userId);

                //只读提交
                if ("r".equals(right)) {
                    boolean rpost = false;
                    if (permission.containsKey("rpost")) {
                        rpost = permission.getBoolean("rpost");
                    }
                    if (rpost) {
                        right = "rp";
                    }
                }

                switch (rights.getType()) {
                    case FormRights.FIELD_RIGHTS:
                        fieldPermission.put(name, right);
                        break;
                    case FormRights.TABLE_RIGHTS:
                        tablePermission.put(name, right);
                        break;
                    case FormRights.OPINION_RIGHTS:
                        opinionPermission.put(name, right);
                        break;
                    default:
                        break;
                }
            }
        }
        permissions.put("field", fieldPermission);
        permissions.put("table", tablePermission);
        permissions.put("opinion", opinionPermission);

        return permissions;
    }

    /**
     * 根据formkey\actDefId\nodeId删除表单权限
     * @param formKey 表单标识
     * @param actDefId 流程定义id
     * @param nodeId 节点id
     * @param parentActDefId 父流程定义id
     * @param platformType 平台类型
     */
    public void deleteRight(String formKey,String actDefId, String nodeId, String parentActDefId, Integer platformType) {
        if (StringUtil.isNotEmpty(nodeId)) {
            if (StringUtil.isNotEmpty(parentActDefId)) {
                formRightsDao.delByActDefIdAndNodeIdAndParentActDefId(actDefId,nodeId,parentActDefId,platformType);
            }else{
                formRightsDao.delByActDefIdAndNodeId(actDefId, nodeId, platformType);
            }
        } else if (StringUtil.isNotEmpty(actDefId)) {
            if (StringUtil.isNotEmpty(parentActDefId)) {
                formRightsDao.delByActDefIdAndParentActDefIdExcNode(actDefId, parentActDefId, platformType);
            }else {
                formRightsDao.delByActDefIdExcNode(actDefId, platformType);
            }
        } else {
            formRightsDao.delByFormKeyExcActDefId(formKey, platformType);
        }
    }

    /**
     * 为url表单增加权限
     * @param request
     * @param formKey
     * @param actDefId
     * @param nodeId
     * @param parentActDefId
     * @param platform
     * @return
     * @throws IOException
     */
    public String addPermissionToUrlForm(HttpServletRequest request, String formKey, String actDefId, String nodeId, String parentActDefId, Integer platform) throws IOException {
        String url = formKey;
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        if (formKey.contains(StringPool.QUESTION_MARK)) {
            formKey = formKey.substring(0, formKey.indexOf(StringPool.QUESTION_MARK));
        }

        String userId = ContextUtil.getCurrentUserId();

        Map<String, Map<String, String>> permissionMap = getByFormKeyAndUserId(formKey, userId, actDefId, nodeId, PlatformType.PC);


        if (!formKey.contains(StringPool.PREFIX_URL)) {
            url = baseUrl + url;
        }
        Cookie[] cookies = request.getCookies();
        Connection conn = Jsoup.connect(url);
        for(Cookie cookie : cookies){
            conn.cookie(cookie.getName(),cookie.getValue());
        }

        Document doc = conn.timeout(3000).get();

        //处理主表字段
        Map<String, String> mainMap = permissionMap.get("field");
        Elements mainTableList = doc.select("input,textarea,select");
        elementAddRights(mainTableList, mainMap);

        //处理意见
        Map<String, String> opinionMap = permissionMap.get("opinion");
        Elements opinionList = doc.select("[name^=opinion]");
        elementAddRights(opinionList, opinionMap);

        String html = doc.outerHtml();
        return html;
    }

    /**
     * 找到元素并根据权限修改属性
     * @param eleList
     * @param mainMap
     */
    private void elementAddRights(Elements eleList, Map<String, String> mainMap) {
        Set<Map.Entry<String, String>> mapSet = mainMap.entrySet();
        for (Map.Entry<String, String> entry : mapSet) {
            String fieldRight = entry.getValue();
            String fieldName = entry.getKey();
            for (Element element : eleList) {
                // 过滤不显示的属性
                String style = element.parent().parent().attr("style");
                if (StringPool.HIDDEN_STYLE.equals(style)) {
                    continue;
                }
//                Element label = element.parent().previousElementSibling();
                String name = element.attr("name");
                String type = element.attr("type");
                String controlType = element.attr("controltype");

                if (!"button".equals(type) && !"hidden".equals(type)) {
                    if (fieldName.equals(name)) {
                        if ("r".equals(fieldRight) || "rp".equals(fieldRight)) {
                            // 只读或只读提交
                            if ("attachment".equals(controlType)) {
                                element.nextElementSibling().attr("style", "display:none");
                            } else if ("checkbox".equals(type) || "radio".equals(type)) {
                                element.attr("disabled", "disabled");
                                if ("checked".equals(element.attr("checked"))) {
                                    element.parent().append(element.val());
                                }
                            } else {
                                element.attr("disabled", "disabled");
                            }

                        } else if ("b".equals(fieldRight)) {

                            // 必填
                            if ("checkbox".equals(type) || "radio".equals(type)) {

                            }else {
                                element.attr("lay-verify", "required");
                            }
                        } else if ("".equals(fieldRight.trim())) {
                            // 没有任何权限
                            element.parent().parent().attr("style", "display:none");
                        } else if ("w".equals(fieldRight.trim())) {

                        }
                    }
                }
            }
        }
    }
}
